package org.urchr.todoist.lib;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

/**
 * @author Kostya
 */
public class Order {
    public static final int NONE = -1;
    public static final int CREATE_PROJECT = 0;
    public static final int ADD_TASK = 1;
    public static final int DELETE_TASK = 2;
    public static final int COMPLETE_TASK = 3;
    public static final int EDIT_TASK = 4;
    
    private int taskType = 0;
    private Object object = null;
    
    public Order(int taskType, Object object){
        this.taskType = taskType;
        this.object = object;
    }
    
    public void executeOrder(Todoist todo)throws IOException{
        Task task = (Task) object;
        JSONParser parser = new JSONParser("");
        switch (taskType){
            case ADD_TASK:
                String url = Todoist.TODO_URL+"addItem?content="+Todoist.encode(task.getName())+
                        "&project_id="+task.getProject().getId()+
                        "&priority="+task.getPriority()+
                        (task.getDate()!=null?("&date_string="+Todoist.encode(task.getDate())):"")+
                        "&token="+todo.getToken();
                Vector data = todo.fetchURL(url, true);
                if(data.size()==0)
                    throw new IOException("Invalid response");
                Hashtable h = (Hashtable) data.elementAt(0);
                task.setId(h.get("id").toString());
                task.setDate(h.get("date_string").toString());
                task.setPriority(h.get("priority").toString());
                task.setOrderAction(Order.NONE);
                return;
            case EDIT_TASK:
                url = Todoist.TODO_URL+"updateItem?content="+Todoist.encode(task.getName())+
                        "&id="+task.getId()+
                        "&priority="+task.getPriority()+
                        (task.getDate()!=null?("&date_string="+Todoist.encode(task.getDate())):"")+
                        "&token="+todo.getToken();
                data = todo.fetchURL(url, true);
                if(data.size()==0)
                    throw new IOException("Invalid response");
                h = (Hashtable) data.elementAt(0);
                task.setDate(h.get("date_string").toString());
                task.setPriority(h.get("priority").toString());
                return;
            case DELETE_TASK:
                url = Todoist.TODO_URL+"deleteItems?project_id="+task.getProjectId()+ //getProject().getId()+
                        "&ids=%5B"+task.getId()+"%5D&token="+todo.getToken();
                data = todo.fetchURL(url, true);

                Todoist.getInstance().DeleteTask(task);
                return;
            case COMPLETE_TASK:
                url = Todoist.TODO_URL+"completeItems?ids=%5B"+task.getId()+"%5D&token="+todo.getToken();
                data = todo.fetchURL(url, true);
                return;
        }
    }
}
